package com.baiytfp.hf.HFDataExchange.action.controller.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baiytfp.hf.baiytfp.common.db.DBManager;
import com.baiytfp.hf.baiytfp.common.util.DateUtil;
import com.baiytfp.hf.baiytfp.common.util.SHACoder;
import com.baiytfp.hf.baiytfp.common.util.StringUtil;
import com.baiytfp.hf.baiytfp.hfutils.*;
import com.baiytfp.hf.HFDataExchange.common.model.base.TableName;
import com.baiytfp.hf.HFDataExchange.common.model.table.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.baiytfp.hf.baiytfp.common.db.HFPager;
import com.baiytfp.hf.baiytfp.framework.base.BaseController;
import com.baiytfp.hf.baiytfp.framework.util.PropertiesUtil;
import com.baiytfp.hf.HFDataExchange.action.service.UserService;
import com.baiytfp.hf.HFDataExchange.common.model.vo.BaseUserVO;
import com.baiytfp.hf.HFDataExchange.common.utils.CommonUtil;
import com.baiytfp.hf.HFDataExchange.common.utils.auth.RuleMatchEnum;

@Controller
@RequestMapping("/service/user")
public class UserSController extends BaseController{

	@Autowired
	public UserService userService;


	@RequestMapping(value="/userlist", method= RequestMethod.POST)
	public ModelAndView userlist(HttpServletRequest request,HttpServletResponse response) throws Exception {
		HFPager hfPager = new HFPager(request);

		Map<String, String> map = new HashMap<String, String>();
		map.put("dept_id", HFRequest.getIstance().getString(request, "dept_id", ""));
		map.put("user_name", HFRequest.getIstance().getString(request, "user_name", ""));
		map.put("user_code", HFRequest.getIstance().getString(request, "user_code", ""));

		hfPager.setParams(map);

		List<Map> list = userService.getUserList(hfPager);


		HFResponse.getIstance().returnResult(response, hfPager.getResult());

		return null;
	}

	//编辑
	@RequestMapping(value="/useredit", method= RequestMethod.POST)
	public ModelAndView useredit(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String key = HFRequest.getIstance().getString(request, "itemid");

		if("".equals(key) || "0".equals(key)){	//新增
			User_account userAccountVO = HFWeb.getIstance().toBean(request, User_account.class);
			userAccountVO.setCreate_time(DateUtil.getCurrentDT());

			//判断帐号
			User_account checkUserAccountVO = HFDBHelper.read(TableName.USER_ACCOUNT, " where user_code=? ", User_account.class, userAccountVO.getUser_code());
			if(checkUserAccountVO != null){
				HFResponse.getIstance().returnResult(response, -1, "当前帐号已经存在，请输入其他帐号", null);
				return null;
			}

			//判断密码
			if(!CommonUtil.matches(HFRequest.getIstance().getString(request, "user_password", ""),userAccountVO.getUser_code())) {
				HFResponse.getIstance().returnResult(response, -1, "密码须含有至少1个以上的数字、字母、特殊符号，长度大于等于8，且不包含帐号", null);
				return null;
			}
			
			//修改密码为MD5
			userAccountVO.setUser_password(HFCodec.getIstance().encoderToMD5(HFRequest.getIstance().getString(request, "user_password", "")));
			userAccountVO.setPwd_expire(new java.sql.Date(DateUtil.addDate(new Date() , PropertiesUtil.getInt("pwd_expire", 90)).getTime()));
			User_info userInfoVO = HFWeb.getIstance().toBean(request, User_info.class);

			//部门信息
			User_dept userDeptVO = new User_dept();
			userDeptVO.setDept_id(HFRequest.getIstance().getString(request, "dept_id"));
			userDeptVO.setGroup_id(HFRequest.getIstance().getString(request,"group_id"));
			userDeptVO.setIs_current(1);
			userDeptVO.setUser_code(userAccountVO.getUser_code());

			//读取角色
			String[] roleArr = request.getParameterValues("user_role");

			//读取岗位
			String[] positionArr = request.getParameterValues("user_position");

			//用户标签
			String tagsStr = "";
			String[] tagsArr = request.getParameterValues("tags");
			if (tagsArr != null) {
				tagsStr = StringUtil.toString(tagsArr, ",", false);
			}
			userInfoVO.setTags(tagsStr);

			long res = -1;
			Connection connection = null;
			try {
				connection = DBManager.getConnection(); // 获取连接池
				DBManager.beginTransaction(connection); // 打开事务
				res =  HFDBHelper.add(connection, TableName.USER_ACCOUNT, userAccountVO);
				res =  HFDBHelper.add(connection, TableName.USER_INFO, userInfoVO);
				res =  HFDBHelper.add(connection, TableName.USER_DEPT, userDeptVO);

				//保存角色
				List<User_role> list_role = new ArrayList<User_role>();
				if(roleArr != null) {
					for (String roleStr : roleArr) {
						User_role userRoleVO = new User_role();
						userRoleVO.setRole_code(roleStr);
						userRoleVO.setUser_code(userAccountVO.getUser_code());
						userRoleVO.setIs_current(0);    //先不使用默认角色

						HFDBHelper.add(connection, TableName.USER_ROLE, userRoleVO);
					}
				}

				//保存岗位
				List<User_position> list_position = new ArrayList<User_position>();
				if(positionArr != null) {
					for (String posiStr : positionArr) {
						User_position userPosiVO = new User_position();
						userPosiVO.setPosi_id(posiStr);
						userPosiVO.setUser_code(userAccountVO.getUser_code());
						userPosiVO.setIs_current(0);    //先不使用默认角色

						HFDBHelper.add(connection, TableName.USER_POSITION, userPosiVO);
					}
				}

				DBManager.commitTransaction(connection); // 提交事务
			} catch (SQLException se) {
				DBManager.rollbackTransaction(connection); // 回滚事务
				throw se;
			} finally {
				DBManager.close(connection); // 涉及事务且外面传进来的连接不在这里关闭
			}

			HFResponse.getIstance().returnResultByRes(response, res);
		}else{	//编辑
			User_account userAccountVO = HFDBHelper.read(TableName.USER_ACCOUNT, " where user_code=? ", User_account.class, key);
			User_info userInfoVO = HFDBHelper.read(TableName.USER_INFO, " where user_code=? ", User_info.class, key);
			User_dept userDeptVO = HFDBHelper.read(TableName.USER_DEPT, " where user_code=? ", User_dept.class, key);

//			userAccountVO = HFWeb.getIstance().toBean(request, userAccountVO);
			userInfoVO = HFWeb.getIstance().toBean(request, userInfoVO);

			//修改密码
			if (!"".equals(HFRequest.getIstance().getString(request, "user_password", ""))) {
				if(!CommonUtil.matches(HFRequest.getIstance().getString(request, "user_password", ""),userInfoVO.getUser_code())) {
					HFResponse.getIstance().returnResult(response, -1, "密码须含有至少1个以上的数字、字母、特殊符号，且长度大于8", null);
					return null;
				}
				
				userAccountVO.setUser_password(HFCodec.getIstance().encoderToMD5(HFRequest.getIstance().getString(request, "user_password", "")));
				userAccountVO.setPwd_expire(new java.sql.Date(DateUtil.addDate(new Date() , PropertiesUtil.getInt("pwd_expire", 90)).getTime()));
			}

			//修改小组
			userDeptVO.setDept_id(HFRequest.getIstance().getString(request,"dept_id",""));
			userDeptVO.setGroup_id(HFRequest.getIstance().getString(request,"group_id",""));

			//读取角色
			String[] roleArr = request.getParameterValues("user_role");

			//读取岗位
			String[] positionArr = request.getParameterValues("user_position");

			//用户标签
			String tagsStr = "";
			String[] tagsArr = request.getParameterValues("tags");
			if (tagsArr != null) {
				tagsStr = StringUtil.toString(tagsArr, ",", false);
			}
			userInfoVO.setTags(tagsStr);

			//修改内容
			long res = -1;
			Connection connection = null;
			try {
				connection = DBManager.getConnection(); // 获取连接池
				DBManager.beginTransaction(connection); // 打开事务
				if (!"".equals(HFRequest.getIstance().getString(request, "user_password", ""))) {	//有修改密码才更新；
					res = HFDBHelper.update(connection, TableName.USER_ACCOUNT, " where user_code = ? ", userAccountVO, new Object[]{userAccountVO.getUser_code()});
				}
				res =  HFDBHelper.update(connection, TableName.USER_INFO, " where user_code = ? ", userInfoVO, new Object[] { userInfoVO.getUser_code() });

				res =  HFDBHelper.update(connection, TableName.USER_DEPT, " where user_code = ? ", userDeptVO, new Object[] { userDeptVO.getUser_code() });

				//先清空之前的角色
				HFDBHelper.delete(connection,TableName.USER_ROLE, " where user_code=? ", new Object[]{userAccountVO.getUser_code()});
				//保存角色
				List<User_role> list_role = new ArrayList<User_role>();
				if(roleArr != null) {
					for (String roleStr : roleArr) {
						User_role userRoleVO = new User_role();
						userRoleVO.setRole_code(roleStr);
						userRoleVO.setUser_code(userAccountVO.getUser_code());
						userRoleVO.setIs_current(0);    //先不使用默认角色

						HFDBHelper.add(connection, TableName.USER_ROLE, userRoleVO);
					}
				}

				//先清空之前的岗位
				HFDBHelper.delete(connection,TableName.USER_POSITION, " where user_code=? ", new Object[]{userAccountVO.getUser_code()});
				//保存岗位
				List<User_position> list_position = new ArrayList<User_position>();
				if(positionArr != null) {
					for (String posiStr : positionArr) {
						User_position userPosiVO = new User_position();
						userPosiVO.setPosi_id(posiStr);
						userPosiVO.setUser_code(userAccountVO.getUser_code());
						userPosiVO.setIs_current(0);    //先不使用默认角色

						HFDBHelper.add(connection, TableName.USER_POSITION, userPosiVO);
					}
				}
				//清除权限缓存
				HFRight.cleanAuth(key);
				DBManager.commitTransaction(connection); // 提交事务
			} catch (SQLException se) {
				DBManager.rollbackTransaction(connection); // 回滚事务
				throw se;
			} finally {
				DBManager.close(connection); // 涉及事务且外面传进来的连接不在这里关闭
			}

			HFResponse.getIstance().returnResultByRes(response, res);
		}

		return null;
	}

	//删除 (支持多个ID, 如 1, 2, 3 这种写法)
	@RequestMapping("/userdel")
	public ModelAndView userdel(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String ids = HFRequest.getIstance().getString(request, "itemid");

		long res = -1;
		Connection connection = null;
		try {
			connection = DBManager.getConnection(); // 获取连接池
			DBManager.beginTransaction(connection); // 打开事务

			Object[] params =  DBManager.getInStrList(ids);

			res = HFDBHelper.delete(connection, TableName.USER_INFO, " where user_code in (" + DBManager.getInCharList( params.length) + ") ",  params);
			res += HFDBHelper.delete(connection, TableName.USER_POSITION, " where user_code in (" + DBManager.getInCharList( params.length) + ") ",  params);
			res += HFDBHelper.delete(connection, TableName.USER_DEPT, " where user_code in (" + DBManager.getInCharList( params.length) + ") ",  params);
			res += HFDBHelper.delete(connection, TableName.USER_ROLE, " where user_code in (" + DBManager.getInCharList( params.length) + ") ",  params);
			res += HFDBHelper.delete(connection, TableName.USER_ACCOUNT, " where user_code in (" + DBManager.getInCharList( params.length) + ") ",  params);

			DBManager.commitTransaction(connection); // 提交事务
		} catch (SQLException se) {
			DBManager.rollbackTransaction(connection); // 回滚事务
			throw se;
		} finally {
			DBManager.close(connection); // 涉及事务且外面传进来的连接不在这里关闭
		}

		HFResponse.getIstance().returnResultByRes(response, res);

		return null;
	}
	
	@RequestMapping("/pwd")
	public ModelAndView savePwd(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		String oldPwd =  HFRequest.getIstance().getString(request, "old");
		String newPwd =  HFRequest.getIstance().getString(request, "new");
		
		long res = -1;
		
		
		
		HFResponse.getIstance().returnResultByRes(response, res);
		return null;
	}

}
